package cn.linshu.security.jwt.service.impl;

import cn.linshu.security.jwt.entity.SysTokenUser;
import cn.linshu.security.jwt.mapper.SysTokenUserMapper;
import cn.linshu.security.jwt.service.SysTokenUserService;
import cn.linshu.security.jwt.util.JwtTokenUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Optional;

/**
 * -*- coding: utf-8 -*-
 *
 * @Author linnin
 * @Name springboot3-labs-master
 * @Time 2025/2/5 21:18
 * @Note
 * @For
 * @Out Copyright© 2025 linnin
 */

/* coding: utf-8 */
@Service("sysTokenUserService")
public class SysTokenUserServiceImpl extends ServiceImpl<SysTokenUserMapper, SysTokenUser> implements SysTokenUserService {
    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Override
public String createToken(SysUserDetails sysUserDetails) {
    String token = jwtTokenUtil.generateToken(sysUserDetails);
    SysTokenUser tokenUser = SysTokenUser.builder()
            .userId(sysUserDetails.getUserId())
            .token(token)
            .createAt(LocalDateTime.now())
            .updateAt(LocalDateTime.now())
            .expireAt(LocalDateTime.now().plusHours(24L))
            .build();

    this.saveOrUpdate(tokenUser);

    return token;
}

    @Override
    public Optional<SysTokenUser> findByUserId(Integer userId) {
        QueryWrapper<SysTokenUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        return Optional.ofNullable(this.getOne(queryWrapper));
    }

}
